<?php

/**
 * uvmcSolrServicesManager implements the singleton design pattern.
 * This class is used to manage a solr service.
 *
 * @package uvmcSolrSearchPlugin
 * @subpackage listener
 * @author  Marc Weistroff <mweistroff@uneviemoinschere.com>
 * @version $Id: uvmcSolrServicesManager.class.php 10 2009-10-22 13:46:49Z gterrain $
 */
class uvmcSolrServicesManager
{
  static
    $instance = null;
    
  protected
    $services = array();

  /**
   * Return the master Solr Service.
   * @return uvmcSolrService
   */
  public function getService($core = '')
  {
    if (false === isset($this->services[$core]))
    {
      $this->createService($core);
    }
    if (!$this->services[$core]->ping())
    {
      throw new sfException("Can't ping this Solr server");
    }

    return $this->services[$core];
  }

  /**
   * Create the master Solr service
   * 
   * @return Apache_Solr_service
   */
  protected function createService($core)
  {
    $host = sfConfig::get('uvmc_solr_service_host', 'localhost');
    $port = sfConfig::get('uvmc_solr_service_port', 8983);
    $path = sfConfig::get('uvmc_solr_service_path', "/solr");

    if (!is_null($host))
    {
      $service = new uvmcSolrService($host, $port, $path.'/'.$core);
      if ($service->ping())
      {
        $this->services[$core] = $service;
        return $this->services[$core];
      }
    }

    throw new sfException("Can't create an Apache_Solr_Service with this configuration.");
  }
  
  /**
   * @return uvmcSolrServicesManager instance
   */
  static function getInstance()
  {
    if(!self::$instance instanceof uvmcSolrServicesManager)
    {
      self::createInstance();
    }
    return self::$instance;
  }

  static function createInstance()
  {
    self::$instance = new uvmcSolrServicesManager();
  }
}
